package com.dependencies.springjdbc.dao;

import java.sql.*;

/**
 * Java有没有工具可以生产6位自增序号数字
 * 2、数据库自增序号
 */
public class DatabaseSerialNumberGenerator {
    private Connection connection;
    private Statement statement;
    
    public DatabaseSerialNumberGenerator() throws SQLException {
        // TODO: 替换为你的数据库URL
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdatabase", "username", "password");
        statement = connection.createStatement();
    }
    
    public String getNextSerialNumber() throws SQLException {
        String query = "INSERT INTO serial_numbers (dummy_column) VALUES (NULL)";
        statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
        ResultSet generatedKeys = statement.getGeneratedKeys();
        if (generatedKeys.next()) {
            return String.format("%06d", generatedKeys.getInt(1));
        } else {
            throw new SQLException("Failed to retrieve serial number.");
        }
    }
    
    public void close() throws SQLException {
        statement.close();
        connection.close();
    }
    
    
    /**
     * 1、内存中生成自增序号
     */
    private static int currentNumber = 0;
    
    public static void main(String[] args) {
        currentNumber++;
        String str =  String.format("%06d", currentNumber); // 格式化为6位数字
        System.out.println(str);
    }
}